<template>
  <el-dialog :title="title" :visible.sync="visible" class="dialog-sm" append-to-body @close="close">
    <el-form ref="formRef" :model="form" label-width="80px" v-loading="loading">
      <el-form-item label="角色名称">
        <el-input v-model="rowData.name" disabled />
      </el-form-item>
      <el-form-item label="权限字符">
        <el-input v-model="rowData.role_key" disabled />
      </el-form-item>
      <el-form-item label="权限范围">
        <el-select v-model="form.data_scope" @change="dataScopeChange">
          <el-option v-for="item in scopeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据权限" v-show="form.data_scope === scopeCustom">
        <el-checkbox v-model="deptExpand" @change="handleTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptNodeAll" @change="handleTreeNodeAll">全选/全不选</el-checkbox>
        <el-checkbox v-model="deptCheckStrictly">父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="treeRef"
          node-key="id"
          :check-strictly="!deptCheckStrictly"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit" :loading="submitting" :disabled="loading">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { infoRoleApi, saveDataScopeApi } from '@/api/system/role'
import { selectDeptApi } from '@/api/system/dept'
import { dataScopeOptions } from './script'

export default {
  name: 'DataScope',
  props: {
    value: Boolean,
    id: Number|String,
  },
  data() {
    return {
      title: '分配数据权限',
      rowData: {},
      loading: false,
      submitting: false,
      form: { data_scope: undefined, dept_ids: [] },
      deptOptions: null,
      deptExpand: true,
      deptNodeAll: false,
      deptCheckStrictly: false,
      defaultProps: { children: "children", label: "name" },
      scopeOptions: dataScopeOptions,
      scopeCustom: 8
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      this.form.id = this.id || undefined
      if(!this.form.id) return this.close(false, '参数错误')
      await this.getRowData()
      await this.getDeptOptions()
      this.loading = false
    },
    async handleSubmit() {
      if (this.submitting) return
      this.submitting = true
      this.form.dept_ids = this.getAllCheckedKeys()
      try {
        await this.$modal.confirm('确定提交表单数据？')
        await saveDataScopeApi(this.form)
        this.close(true, '操作成功')
      } catch (e) {}
      this.submitting = false
    },
    async getRowData() {
      try {
        const { info } = await infoRoleApi(this.form.id)
        this.dataToForm(this.form, info)
        this.rowData = info
      } catch (error) {
        this.close()
      }
    },
    async getDeptOptions() {
      try {
        const { list } = await selectDeptApi()
        this.deptOptions = this.listToTree(list)
        this.$nextTick(()=>{
          this.form.dept_ids.map(id=>{
            this.$refs.treeRef.setChecked(id,true,false)
          })
        })
      }catch (e) {}
    },
    close(submit = false, msg) {
      if (submit === true) this.$emit('submit')
      this.$emit('close', submit === true)
      if (msg) submit === true ? this.$modal.msgSuccess(msg) : this.$modal.msgError(msg)
      this.visible = false
    },
    dataScopeChange(value) {
      if(value !== this.scopeCustom) this.$refs.treeRef.setCheckedKeys([])
    },
    handleTreeExpand(checked) {
      let treeList = this.deptOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.treeRef.store.nodesMap[treeList[i].id].expanded = checked
      }
    },
    handleTreeNodeAll(checked) {
      this.$refs.treeRef.setCheckedNodes(checked ? this.deptOptions: [])
    },
    getAllCheckedKeys() {
      let checkedKeys = this.$refs.treeRef.getCheckedKeys()
      let halfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
  }
}
</script>
